package com.cqeec.gams.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cqeec.gams.entity.FunctionalModule;
import com.cqeec.gams.service.FunctionalModuleService;

@RestController
@RequestMapping("/api/function/")
public class FunctionRestController {
	@Autowired
	private FunctionalModuleService fmService;

	@RequestMapping("/delete.html")
	public Map<String, Object> delete(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 判断功能是否被授予角色，有不能删除
		int total = fmService.countRolePermission(id);
		if (total > 0) {
			map.put("code", 1);
			map.put("message", "功能被授予角色，不能删除!");
			return map;
		}
		// 如果删除的是功能组，判断其下面是否有模块，有不能删除
		FunctionalModule fm = fmService.findById(id);
		String type = fm.getType();
		if ("1".equals(type)) {
			total = fmService.countSubFunctionalModule(id);
			if (total > 0) {
				map.put("code", 2);
				map.put("message", "功能组下有功能模块，不能删除!");
				return map;
			}
		}
		try {
			fmService.delete(id);
			map.put("code", 0);
			map.put("message", "删除功能成功!");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 3);
			map.put("message", "删除功能失败!");
		}
		return map;
	}

	@GetMapping("/list")
	public List<FunctionalModule> list() {
		return fmService.findAll();
	}
}
